package org.example.ancestral_common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.support.MissingServletRequestPartException;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalException {
    private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);

    // 处理参数异常 IllegalArgumentException
    @ExceptionHandler({IllegalArgumentException.class})
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentException(Exception e) {
        logger.error("处理参数异常", e);
        return buildErrorResponse(HttpStatus.BAD_REQUEST, 500, e.getMessage(), "处理参数异常");
    }

    // 处理空指针异常和缺少请求部分异常
    @ExceptionHandler({NullPointerException.class, MissingServletRequestPartException.class})
    public ResponseEntity<Map<String, Object>> handleNullPointerException(Exception e) {
        logger.error("空指针异常或缺少请求部分异常", e);
        return buildErrorResponse(HttpStatus.BAD_REQUEST, 500, e.getMessage(), "空指针异常,请查看参数是否完整");
    }

    // 处理IO异常
    @ExceptionHandler(IOException.class)
    public ResponseEntity<Map<String, Object>> handleIOException(IOException e) {
        logger.error("IO写入异常", e);
        return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 500, e.getMessage(), "IO写入异常");
    }

    // 处理运行时异常
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException e) {
        logger.error("运行时异常", e);
        return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 500, e.getMessage(), "服务器内部错误");
    }

    // 处理未被其他方法捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleGenericException(Exception e) {
        logger.error("未知异常", e);
        return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 500, e.getMessage(), "未知异常，请联系管理员");
    }

    // 构建错误响应
    private ResponseEntity<Map<String, Object>> buildErrorResponse(HttpStatus httpStatus, int code, String message, String data) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", code);
        response.put("message", message);
        response.put("data", data);
        return ResponseEntity.status(httpStatus).body(response);
    }
}